import os
import base64
import urllib
import requests

def get_license_plate(token, path):
    print(path)
    print(os.path.exists(path))
    url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token={token}"
    # image 可以通过 get_file_content_as_base64("C:\fakepath\车牌1.jpg",True) 方法获取
    # image = get_file_content_as_base64(path, True)
    with open(path, "rb") as f:
        image = base64.b64encode(f.read())
    # payload=f'image={image}&multi_detect=false&multi_scale=false'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    payload = {
        "image": image,
        "multi_detect": "false",
        "multi_scale": "false"
    }
    response = requests.post(url, headers=headers, data=payload)
    print(response.text)
    if response.status_code != 200:
        raise Exception("识别请求失败")
    result = response.json()
    return result.get("words_result",{}).get("number","")


def get_baidu_access_token(API_KEY, SECRET_KEY):
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    print("获取TOKEN")
    url = "https://aip.baidubce.com/oauth/2.0/token"
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    resp = requests.post(url, data=params, headers=headers)
    return str(resp.json().get("access_token"))


def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded 
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content
